//
//  UserInfoViewController.m
//  WonderfulNotes
//
//  Created by 千锋 on 16/1/11.
//  Copyright © 2016年 andy. All rights reserved.
//

#import "UserInfoViewController.h"
//提供文件相关功能接口
#import <BmobSDK/BmobProFile.h>
#import "headImageView.h"

typedef NS_ENUM(NSInteger,ChosePhotoType) {
    
    ChosePhotoTypeAlbum,
    ChosePhotoTypeCamera

};

@interface UserInfoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet headImageView *userIcon;

@property (weak, nonatomic) IBOutlet UIView *userIcon_back;

@end

@implementation UserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.userIcon_back.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"usericon_background"]];
    
    [self updateUserInfo];
    // Do any additional setup after loading the view.
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    UIImage * userIcon = [[InfoStore sharedStore] imageForKey:@"UserIcon"];
    if (!userIcon) {
        self.userIcon.image = [UIImage imageNamed:@"avatar_default_big"];
    }else{
        self.userIcon.image = userIcon;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}

-(void)updateUserInfo{
    
    //获取到当前的用户
    BmobUser * user = [BmobUser getCurrentUser];
    if (user) {
        
        //获取用头像
        [self.userIcon sd_setImageWithURL:[NSURL URLWithString:[user objectForKey:@"userIconUrl"]]];
    }else{
        
        self.userIcon.image = [UIImage imageNamed:@"avatar_default_big"];
    }
    
}

/**点击头像上传图片*/
- (IBAction)userIconTapAction:(UITapGestureRecognizer *)sender {
    
        //创建一个弹出提示框
        UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"请选取打开方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction * album = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //相片选取方法调用
            [self chosePhoto:ChosePhotoTypeAlbum];
    
        }];
    
        UIAlertAction * camera = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self chosePhoto:ChosePhotoTypeCamera];
    
        }];
    
        UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
    
        //添加到UIAlertController
        [alert addAction:album];
        [alert addAction:camera];
        [alert addAction:cancel];
        
        [self presentViewController:alert animated:YES completion:^{
            
        }];
}

-(void)chosePhoto:(ChosePhotoType)type{
    
    UIImagePickerController * picker = [[UIImagePickerController alloc]init];
    
    picker.delegate = self;
    picker.editing = YES;
    picker.allowsEditing = YES;
    
    if (type==ChosePhotoTypeAlbum) {
        //从相册中选区照片
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
    }else if (type==ChosePhotoTypeCamera){
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:@"相机不可用"];
            return;
        }
        
    }
    [self presentViewController:picker animated:YES completion:^{
            
    }];

}
#pragma mark - 选取图片

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //获取的图像为编辑后的图像
    UIImage * img = info[UIImagePickerControllerEditedImage];
    
    //1.存储到本地沙河路径(用户图标)
    [[InfoStore sharedStore] setImage:img forKey:@"UserIcon"];
    //上传头像
    self.userIcon.image = img;
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
    //2.上传到服务器
    [self uploadImageWithImage:img];
        
    }];
    
    
}

/** 上传图片到bmob服务器*/

-(void)uploadImageWithImage:(UIImage *)img{
    
    NSData * data = UIImageJPEGRepresentation(img, 0.5);
    
    [BmobProFile uploadFileWithFilename:@"userIcon" fileData:data block:^(BOOL isSuccessful, NSError *error, NSString *filename, NSString *url, BmobFile *file) {
        
        [SVProgressHUD showWithStatus:@"上传图片..." maskType:SVProgressHUDMaskTypeClear];
        
        if (isSuccessful) {
            
            NSLog(@"url = %@",url);
            NSLog(@"file = %@",file);
            //将上传的图片和用户关联起来
            BmobUser * user = [BmobUser getCurrentUser];
            [user setObject:file.url forKey:@"userIconUrl"];
            /**
             *	后台更新BmobObject对象
             *	@param	block	返回更新的结果是成功还是失败
             */
            [user updateInBackgroundWithResultBlock:^(BOOL isSuccessful, NSError *error) {
               
                if (isSuccessful) {
                    
                    [SVProgressHUD dismiss];
                    
                    [self.userIcon sd_setImageWithURL:[NSURL URLWithString:file.url]];
                    [[NSNotificationCenter defaultCenter] postNotificationName:USER_REFRESH_NOTICE object:nil];
                }else{
                    
                    [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
            
                }
                
            }];
            
        }else{
            
            [SVProgressHUD showErrorWithStatus:[error localizedDescription]];
        }
        
    } progress:^(CGFloat progress) {
        
        //显示上传的进度
        //[SVProgressHUD showProgress:progress];
        
    }];
    
}
- (IBAction)loginOutBtnClicked:(UIButton *)sender {
    
    //退出登录
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"是否确定要退出登录" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction * cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction * quit = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [BmobUser logout];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:USER_REFRESH_NOTICE object:nil];
        
    }];
    
    [alert addAction:cancel];
    [alert addAction:quit];
    
    [self presentViewController:alert animated:YES completion:^{
       
    }];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
